package com.sailing.lianxi.util.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.NoSuchElementException;
import java.util.Properties;

public class PropertiesUtils {

	private Properties props;
	
	/**
	 * 通过文件生成配置文件对象
	 * @param path
	 */
	public PropertiesUtils(File file){
		InputStream in = null;
		 props = new Properties();
		try {
			in = new FileInputStream(file);
			props.load(in);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			System.out.println("加载文件失败："+file.getPath());
		}finally{
			colseInputStream(in);
		}
	}
	
	/**
	 * 通过配置文件路径加载配置，主要处理resource目录下的文件
	 * @param path
	 */
	public PropertiesUtils(String path){
	 props = new Properties();
	 InputStream in = null;
	   try {
		   in = PropertiesUtils.class.getClassLoader().getResourceAsStream(path);
		   props.load(in);
		} catch (Exception e) {
			System.out.println("加载配置文件失败："+path);
		}finally{
			colseInputStream(in);
		}
	}
	
	public String getProperty(String key){
		return props.getProperty(key);
	}
	
	public String getProperty(String key,String defaultValue){
		return props.getProperty(key,defaultValue);
	}
	
	public Integer getInteger(String key){
		String value = value(key);
		if(null==value){
			throw new NoSuchElementException();
		}
		return Integer.valueOf(value);
	}
	
	public String value(String key){
		return props.getProperty(key);
	}
	
	/**
	 * 关闭InputStream
	 * @param in
	 */
	private void colseInputStream(InputStream in){
		if(null != in){
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
				System.out.println("流关闭失败...");
			}
		}
	}
}
